package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WarehouseErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.log.pojo.dto.RuleBusinessLogDTO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivityEditAttrUpdateVO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.warehouse.pojo.dto.ProductWarehouseMapDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WareHouseEditAttrUpdateDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WareHouseUpdateDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseDeleteBatchDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseIdListDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseListDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseUpdateBatchDTO;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseUpdateByBusinessRuleDTO;
import com.xbongbong.pro.warehouse.pojo.vo.ProductWarehouseMapVO;
import com.xbongbong.pro.warehouse.pojo.vo.WarehouseDeleteBatchVO;
import com.xbongbong.pro.warehouse.pojo.vo.WarehouseIdListVO;
import com.xbongbong.pro.warehouse.pojo.vo.WarehouseListVO;
import com.xbongbong.saas.analytical.impl.WareHouseValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.WarehouseOristockEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.subform.ProductWarehouseSubFormEnum;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WarehouseOristockModel;
import com.xbongbong.saas.model.WarehouseUserModel;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/2/15 15:27
 * @since v1.0
 */
@Service("warehouseService")
public class WarehouseServiceImpl implements WarehouseService {

    private static final Logger LOG = LoggerFactory.getLogger(WarehouseServiceImpl.class);

    @Resource
    private WarehouseUserModel warehouseUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    @Lazy
    private RuleBusinessLogger ruleBusinessLogger;

    @Resource
    private OriStockServiceImpl oriStockService;
    @Resource
    private WarehouseOristockModel warehouseOristockModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private LogHandleHelp logHandleHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private WareHouseValidateAnalyticalServiceImpl wareHouseAnalyticalService;
    @Resource
    private ProductModel productModel;


    /**
     * 仓库保存前saas特殊校验
     *
     * @param validateDataDTO saas特殊校验数据入参
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/18
     */
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        wareHouseAnalyticalService.beforeSave(validateDataDTO);
    }

    /**
     * 仓库保存后逻辑
     *
     * @param saasFormSaveDTO saas保存数据
     * @throws XbbException 业务异常
     * @author feng.zheng
     */
    @Override
    public void afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        Boolean isNew = saasFormSaveDTO.getIsNew();
        String corpid = saasFormSaveDTO.getCorpid();
        JSONObject newData = saasFormSaveDTO.getNewData();
        JSONObject oldData = saasFormSaveDTO.getOldData();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long warehouseId = newPaasFormDataEntity.getId();
        String warehouseName = FastJsonHelper.getStringFromFormData(newData, WarehouseEnum.WAREHOUSE_NAME.getAttr());
        String oldWarehouseName = FastJsonHelper.getStringFromFormData(oldData, WarehouseEnum.WAREHOUSE_NAME.getAttr());
        JSONArray depArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_DEP_ID.getAttr());
        JSONArray userArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_ID.getAttr());
        List<Long> depList = new ArrayList<>();
        List<String> userList = new ArrayList<>();
        List<String> containUserIdList = new ArrayList<>();
        List<Long> containDepIdList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (depArray != null) {
            depList = depArray.toJavaList(Long.class);
        }
        if (userArray != null) {
            userList = userArray.toJavaList(String.class);
        }
        if (!isNew) {
            if (!Objects.equals(warehouseName, oldWarehouseName)) {
                // 编辑时仓库名称改变时更新仓库产品表的仓库名称
//                productWarehouseModel.updateWarehouseNameByWarehouseId(warehouseName, corpid, warehouseId);
                Runnable runnable = () -> {
                    try {
                        updateProductLinkWarehouseName(corpid, warehouseId, warehouseName);
                    } catch (Exception e) {
                        LOG.error("编辑仓库名称后更新产品的关联仓库字段", e);
                    }
                };
                threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            }
            // 编辑仓库时删除删掉的负责人和负责部门
            deleteOldWarehouseUserList(corpid, warehouseId, depList, userList, containUserIdList, containDepIdList, param);
        }
        userList.removeAll(containUserIdList);
        depList.removeAll(containDepIdList);
        // 建立仓库协同团队
        buildWarehouseTeam(corpid, userList, depList, warehouseId, param);
    }



    @Override
    public WarehouseListVO getManagetWarehouses(WarehouseListDTO warehouseListDTO) {
        WarehouseListVO warehouseListVO = new WarehouseListVO();
        List<WarehouseEntityExt> resultWarehouses;
        String corpid = warehouseListDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        UserVO userVO = warehouseListDTO.getLoginUser();
        boolean isAdminOrBoss = userVO.isAdminOrBoss();
        if (Objects.nonNull(warehouseListDTO.getUserEntity())) {
            UserEntity userEntity = warehouseListDTO.getUserEntity();
            BeanUtil.copyProperties(userEntity, userVO);
            isAdminOrBoss = userModel.isBoss(userEntity) || userEntity.isWarehouseManager();
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        if (Objects.equals(userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WAREHOUSE.getCode(), null), 5)) {
            isAdminOrBoss = true;
        }
        if (!isAdminOrBoss){
            List<WarehouseUserEntity> warehouseManagerList = getWarehouseManagerList(userVO);
            Set<Long> warehouseIdIn = new HashSet<>();
            warehouseIdIn.add(-1L);
            for (WarehouseUserEntity entity : warehouseManagerList) {
                warehouseIdIn.add(entity.getDataId());
            }
            param.put("idIn", warehouseIdIn);
            param.put("corpid", corpid);
            param.put("del", 0);
            resultWarehouses = warehouseModel.findEntitys(param);
        } else {
            param.put("corpid", corpid);
            param.put("del", 0);
            resultWarehouses = warehouseModel.findEntitys(param);
        }
        warehouseListVO.setWarehouseList(resultWarehouses);
        return warehouseListVO;
    }

    @Override
    public ProductWarehouseMapVO getSelectProductWarehouses(ProductWarehouseMapDTO productWarehouseMapDTO) throws XbbException {
        ProductWarehouseMapVO productWarehouseMapVO = new ProductWarehouseMapVO();
        String corpid = productWarehouseMapDTO.getCorpid();

        Map<String, FieldAttrEntity> nowProductExplainMap = productWarehouseMapDTO.getNowProductExplainMap();
        if (nowProductExplainMap == null) {
            nowProductExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", 0);
            param.put("saasMark", 1);
            param.put("businessType", XbbRefTypeEnum.PRODUCT.getCode());
            List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(param);
            if (!formExplainList.isEmpty()) {
                PaasFormExplainEntity paasFormExplainEntity = formExplainList.get(0);
                List<FieldAttrEntity> nowProductExplainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                for (FieldAttrEntity entity : nowProductExplainList) {
                    nowProductExplainMap.put(entity.getSaasAttr(), entity);
                }
            }
        }
        // 成本小数精度控制
        Integer costAccuracy = AttrDecimalPrecisionHelper.DEFAULT_PRECISION;
        FieldAttrEntity costExplain = nowProductExplainMap.get("cost");
        if (costExplain != null) {
            costAccuracy = costExplain.getAccuracy();
        }
        costAccuracy = costAccuracy == null ? AttrDecimalPrecisionHelper.DEFAULT_PRECISION : costAccuracy;

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.PRODUCT_ID), productWarehouseMapDTO.getProductId()));
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_CHECKED), 1));
        boolQueryBuilder.mustNot(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), 0L));
        List<Long> warehouseIdList = new ArrayList<>();
        boolean isMaxPermission = productWarehouseMapDTO.getLoginUser().isMaxDataPermission();
        if (!isMaxPermission){
            //非超管加一下权限
            warehouseIdList = warehouseService.getWarehouseIdsByPermission(productWarehouseMapDTO.getLoginUser(),productWarehouseMapDTO.getLoginUser().getDepSet());
            if (warehouseIdList.size() == 1 && warehouseIdList.contains(-1L)){
                Map<String, JSONArray> resultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                resultMap.put(BusinessConstant.ALL_WAREHOUSE_ARRAY, new JSONArray());
                resultMap.put(BusinessConstant.USER_WAREHOUSE_ARRAY, new JSONArray());
                productWarehouseMapVO.setProductWarehouseMap(resultMap);
                return productWarehouseMapVO;
            }
            boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID),warehouseIdList));
        }
        List<String> productWarehouseFieldList = new ArrayList<>();
        productWarehouseFieldList.add(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.WAREHOUSE_ID));
        productWarehouseFieldList.add(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.WAREHOUSE_NAME));
        productWarehouseFieldList.add(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.NUM));
        productWarehouseFieldList.add(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.COST));
        List<PaasFormDataEntity> productWarehouseList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE,boolQueryBuilder,PaasFormDataEntity.class,productWarehouseFieldList);
        List<ProductWarehouseEntity> productWarehouseEntities = transferSubFormHelper.transferFormDataToProductWarehouseList(productWarehouseList);

        List<WarehouseEntityExt> allWarehouseList = null;
        if (Objects.equals(productWarehouseMapDTO.getAllWarehouse(), 1)) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("del", 0);
            if (!isMaxPermission){
                params.put("idIn",warehouseIdList);
            }
            // 该公司所有仓库
            allWarehouseList = warehouseModel.findEntitys(params);
        }

        // 获取当前用户负责的仓库
//        WarehouseListDTO warehouseListDTO = new WarehouseListDTO();
//        BeanUtil.copyProperties(productWarehouseMapDTO, warehouseListDTO);
//        WarehouseListVO warehouseListVO = warehouseService.getManagetWarehouses(warehouseListDTO);
//        if (Objects.isNull(warehouseListVO)) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
//        }
////        List<WarehouseEntityExt> managerWarehouseList = warehouseListVO.getWarehouseList();
//        List<Long> managerWarehouseIdList = new ArrayList<>();
//        for (WarehouseEntityExt warehouseEntity : managerWarehouseList) {
//            managerWarehouseIdList.add(warehouseEntity.getId());
//        }

        JSONArray warehouseArray = new JSONArray();
        for (ProductWarehouseEntity productWarehouse : productWarehouseEntities) {
            // 产品所在仓库
            Long warehouseId = productWarehouse.getWarehouseId();
//            if (managerWarehouseIdList.contains(warehouseId)) {
                // 用户负责的仓库
                JSONObject warehouseObjArray = new JSONObject();
                warehouseObjArray.put(StringConstant.SAAS_LINK_BUSINESS_ID, warehouseId);
                warehouseObjArray.put(StringConstant.VALUE, productWarehouse.getWarehouseName());
                warehouseObjArray.put(StringConstant.NUM, productWarehouse.getNum());
                double productCost = productWarehouse.getCost() == null ? 0D : productWarehouse.getCost();
                warehouseObjArray.put(StringConstant.PRODUCT_COST, Arith.round(productCost, costAccuracy));
                warehouseArray.add(warehouseObjArray);
//            }
        }
        JSONArray array = new JSONArray();
        if (allWarehouseList != null) {
            for (WarehouseEntityExt warehouseEntity : allWarehouseList) {
                // 入库时可以选择用户负责的所有仓库，包括未建立产品-仓库关联关系的仓库
                Long warehouseId = warehouseEntity.getId();
//                if (managerWarehouseIdList.contains(warehouseId)) {
                    // 用户负责的仓库
                    JSONObject dataList = warehouseEntity.getData();
                    JSONObject allWarehouseObj = new JSONObject();
                    allWarehouseObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, warehouseId);
                    allWarehouseObj.put(StringConstant.VALUE, dataList.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                    allWarehouseObj.put(StringConstant.NUM, 0);
                    // TODO 成本
                    allWarehouseObj.put(StringConstant.PRODUCT_COST, 0);
                    for (int i = 0; i < warehouseArray.size(); i++) {
                        JSONObject hasWarehouseObj = warehouseArray.getJSONObject(i);
                        Long hasWarehouseId = hasWarehouseObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
                        if (Objects.equals(warehouseId, hasWarehouseId)) {
                            allWarehouseObj.put(StringConstant.NUM, hasWarehouseObj.get(StringConstant.NUM));
                            allWarehouseObj.put(StringConstant.PRODUCT_COST, hasWarehouseObj.get(StringConstant.PRODUCT_COST));
                            break;
                        }
                    }
                    array.add(allWarehouseObj);
//                }
            }
        }
        Map<String, JSONArray> resultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        resultMap.put(BusinessConstant.ALL_WAREHOUSE_ARRAY, array);
        resultMap.put(BusinessConstant.USER_WAREHOUSE_ARRAY, warehouseArray);
        productWarehouseMapVO.setProductWarehouseMap(resultMap);
        return productWarehouseMapVO;
    }

    /**
     * 获取用户负责的仓库
     *
     * @param user 当前用户
     * @return 创建时间 2018/9/4 14:24
     * @author GuoJun.HU
     * @since 3.27
     */
    @Override
    public List<WarehouseUserEntity> getWarehouseManagerList(UserVO user) {
        //老板 管理员 仓库主管可以查看所有的仓库
        if (!user.isAdminOrBoss()) {
            //查看自己所在部门负责的仓库
            List<WarehouseUserEntity> departmentManagerList = getWarehouseManagerListBaseDepartment(user);
            //查看自己主负责的仓库
            List<WarehouseUserEntity> userManagerList = getWarehouseManagerListBaseUser(user);
            //得到全部负责的仓库数据
            List<WarehouseUserEntity> warehouseManagerList = new ArrayList<>(departmentManagerList);
            for (WarehouseUserEntity userManager : userManagerList) {
                boolean isRepeat = false;
                for (WarehouseUserEntity departManager : departmentManagerList) {
                    if (Objects.equals(userManager.getId(), departManager.getId())) {
                        isRepeat = true;
                        break;
                    }
                }
                if (!isRepeat) {
                    warehouseManagerList.add(userManager);
                }
            }
            return warehouseManagerList;
        } else {
            Map<String, Object> param = new HashMap<>(16);
            param.put("corpid", user.getCorpid());
            param.put("del", 0);
            return warehouseUserModel.findEntitys(param);
        }
    }

    /**
     * 获取用户所在部门负责的仓库
     *
     * @param user 当前用户
     * @return 创建时间 2018/9/4 14:24
     * @author GuoJun.HU
     * @since 3.27
     */
    public List<WarehouseUserEntity> getWarehouseManagerListBaseDepartment(UserVO user) {
        String corpid = user.getCorpid();
        // 获取当前用户所属部门
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(user, userEntity);
        List<Long> belongDepList = userModel.getUserBelongDeptIdList(userEntity, false);

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("type", 1);
        List<WarehouseUserEntity> allWarehouseManagerList = warehouseUserModel.findEntitys(param);

        List<WarehouseUserEntity> warehouseManagerList = new ArrayList<>();
        for (WarehouseUserEntity warehouseManager : allWarehouseManagerList) {
            String depIdStr = warehouseManager.getRelationId();
            Long depId = Long.valueOf(depIdStr);
            if (Objects.equals(depId, 1L)) {
                // 负责部门为全公司
                warehouseManagerList.add(warehouseManager);
                continue;
            }
            // 获取当前部门的子部门
            List<Long> subDepIdList = departmentModel.getSubDepIdList(corpid, Collections.singleton(depId));
            subDepIdList.retainAll(belongDepList);
            if (!subDepIdList.isEmpty()) {
                warehouseManagerList.add(warehouseManager);
            }
        }

        return warehouseManagerList;
    }

    /**
     * 获取用户负责的仓库(不包含所属部门负责)
     *
     * @param user 当前用户
     * @return 创建时间 2018/9/4 14:24
     * @author GuoJun.HU
     * @since 3.27
     */
    public List<WarehouseUserEntity> getWarehouseManagerListBaseUser(UserVO user) {
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", user.getCorpid());
        param.put("del", 0);
        param.put("type", 0);
        param.put("relationId", user.getUserId());
        return warehouseUserModel.findEntitys(param);
    }

    /**
     * 编辑仓库时删除删掉的负责人和负责部门
     *
     * @param corpid            公司id
     * @param warehouseId       仓库id
     * @param depList           传来的部门id集合
     * @param userList          传来的员工id集合
     * @param containUserIdList 编辑没有更改的员工id集合
     * @param containDepIdList  编辑没有更改的部门id集合
     * @author feng.zheng
     * @date 2019/2/18 10:19
     */
    private void deleteOldWarehouseUserList(String corpid, Long warehouseId, List<Long> depList, List<String> userList, List<String> containUserIdList, List<Long> containDepIdList, Map<String, Object> param) {
        param.clear();
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("warehouseId", warehouseId);
        List<WarehouseUserEntity> warehouseUserEntityList = warehouseUserModel.findEntitys(param);
        List<String> deleteManageUserIdList = new ArrayList<>();
        List<Long> deleteManageDepIdList = new ArrayList<>();
        for (WarehouseUserEntity warehouseUserEntity : warehouseUserEntityList) {
            if (Objects.equals(warehouseUserEntity.getType(), 0)) {
                String managerUserId = warehouseUserEntity.getRelationId();
                if (userList.contains(managerUserId)) {
                    containUserIdList.add(managerUserId);
                } else {
                    deleteManageUserIdList.add(managerUserId);
                }
            } else {
                Long managerDepId = Long.valueOf(warehouseUserEntity.getRelationId());
                if (depList.contains(managerDepId)) {
                    containDepIdList.add(managerDepId);
                } else {
                    deleteManageDepIdList.add(managerDepId);
                }
            }
        }
        if (!deleteManageUserIdList.isEmpty()) {
            warehouseUserModel.deleteByUserIdIn(corpid, warehouseId, deleteManageUserIdList, 0);
        }
        if (!deleteManageDepIdList.isEmpty()) {
            warehouseUserModel.deleteByDepIdIn(corpid, warehouseId, deleteManageDepIdList, 1);
        }
    }

    /**
     * 建立仓库协同团队
     *
     * @param corpid      公司id
     * @param userList    员工id集合
     * @param depList     部门id集合
     * @param warehouseId 仓库id
     * @param modelMap    参数
     * @author feng.zheng
     * @date 2019/2/18 10:38
     */
    private void buildWarehouseTeam(String corpid, List<String> userList, List<Long> depList, Long warehouseId, Map<String, Object> modelMap) throws XbbException {
        if (!userList.isEmpty()) {
            modelMap.clear();
            modelMap.put("corpid", corpid);
            modelMap.put("del", 0);
            modelMap.put("userIdIn", userList);
            List<UserEntity> userEntityList = userModel.findEntitys(modelMap);
            Map<String, String> userMap = new HashMap<>(16);
            for (UserEntity user : userEntityList) {
                userMap.put(user.getUserId(), user.getName());
            }

            for (String managerId : userList) {
                WarehouseUserEntity warehouseUserEntity = new WarehouseUserEntity();
                warehouseUserEntity.setCorpid(corpid);
                warehouseUserEntity.setDataId(warehouseId);
                warehouseUserEntity.setRelationId(managerId);
                String managerName = "";
                managerName = userMap.get(managerId);
                if (managerName == null || managerName.length() <= 0) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100065);
                }
                warehouseUserEntity.setRelationName(StringUtil.filterEmoji(managerName));
                warehouseUserEntity.setType(0);
                warehouseUserModel.insert(warehouseUserEntity);
            }
        }

        if (!depList.isEmpty()) {
            modelMap.clear();
            modelMap.put("corpid", corpid);
            modelMap.put("del", 0);
            modelMap.put("idIn", depList);
            List<DepartmentEntity> departmentList = departmentModel.findEntitys(modelMap);
            Map<Long, String> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (DepartmentEntity department : departmentList) {
                departmentMap.put(department.getId(), department.getName());
            }

            for (Long depId : depList) {
                WarehouseUserEntity warehouseManager = new WarehouseUserEntity();
                warehouseManager.setCorpid(corpid);
                warehouseManager.setDataId(warehouseId);
                warehouseManager.setType(1);
                warehouseManager.setRelationId(Objects.toString(depId, ""));
                String managerName = "";
                if (departmentMap.containsKey(depId)) {
                    managerName = departmentMap.get(depId);
                }
                warehouseManager.setRelationName(StringUtil.filterEmoji(managerName));
                warehouseUserModel.insert(warehouseManager);
            }
        }
    }

    /**
     * 筛选仓库
     *
     * @return 如果传入了仓库，则筛选此仓库，否则筛选全公司或下属和自己的仓库
     * @author 周智
     * 创建时间 2017-12-15 11:09
     */
    @Override
    public WarehouseIdListVO getWarehouseIds(WarehouseIdListDTO warehouseIdListDTO) {
        WarehouseIdListVO warehouseIdListVO = new WarehouseIdListVO();
        Long warehouseId = warehouseIdListDTO.getWarehouseId();
        String corpid = warehouseIdListDTO.getCorpid();
        UserVO userVO = warehouseIdListDTO.getLoginUser();
        List<Long> warehouseIds = new ArrayList<>();
        if (warehouseId != null && warehouseId != 0) {
            warehouseIds.add(warehouseId);
        } else {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", 0);

            // 获取下属负责的仓库
            if (!warehouseIdListDTO.getLoginUser().isAdminOrBoss()) {
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(userVO, userEntity);
                Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WAREHOUSE.getCode(), null);
                List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, warehouseIdListDTO.getUserId(), warehouseIdListDTO.getCorpid(), BasicConstant.ZERO, true);
                userIdIn.add(userVO.getUserId());
                if (userIdIn.isEmpty()) {
                    userIdIn.add("-1");
                }
                List<UserEntity> subUserList = userModel.getByUserIdIn(corpid, userIdIn, true) ;
                Set<Long> houseIdIn = new HashSet<>();
                houseIdIn.add(-1L);
                WarehouseListDTO warehouseListDTO = new WarehouseListDTO();
                BeanUtil.copyProperties(warehouseIdListDTO, warehouseListDTO);
                for (UserEntity subUser : subUserList) {
                    warehouseListDTO.setUserEntity(subUser);
                    WarehouseListVO warehouseListVO = getManagetWarehouses(warehouseListDTO);

                    List<WarehouseEntityExt> warehouseList = warehouseListVO.getWarehouseList();
                    for (WarehouseEntityExt warehouseEntity : warehouseList) {
                        houseIdIn.add(warehouseEntity.getId());
                    }
                }
                param.put("houseIdIn", houseIdIn);
            }

            List<WarehouseEntityExt> warehouseEntitys = warehouseModel.findEntitys(param);
            for (WarehouseEntityExt warehouseEntity : warehouseEntitys) {
                warehouseIds.add(warehouseEntity.getId());
            }
        }
        warehouseIdListVO.setWarehouseIdIn(warehouseIds);
        return warehouseIdListVO;
    }


    @Override
    public WarehouseDeleteBatchVO deleteBatch(WarehouseDeleteBatchDTO warehouseDeleteBatchDTO) throws XbbException {
        WarehouseDeleteBatchVO warehouseDeleteBatchVO = new WarehouseDeleteBatchVO();
        try {
            String corpid = warehouseDeleteBatchDTO.getCorpid();
            List<Long> dataIdIn = warehouseDeleteBatchDTO.getDataIdList();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid",corpid);
            param.put("idIn",dataIdIn);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<WarehouseEntityExt> warehouseList = warehouseModel.findEntitys(param);
            if (Objects.isNull(warehouseList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            UserVO userVO = warehouseDeleteBatchDTO.getLoginUser();
            Set<Long> dataIdSet = new HashSet<>(dataIdIn);
            if (!userVO.isAdminOrBoss()) {
                boolean isManager = false;
                List<WarehouseUserEntity> warehouseUserList = getWarehouseManagerList(userVO);
                for (WarehouseUserEntity warehouseManager : warehouseUserList) {
                    if (dataIdSet.contains(warehouseManager.getDataId())) {
                        isManager = true;
                        break;
                    }
                }
                if (!isManager) {
                    throw new XbbException(WarehouseErrorCodeEnum.API_ERROR_244009);
                }
            }
            checkStockDoc(warehouseList,dataIdSet,corpid);
//            Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            modelMap.put("corpid", corpid);
//            modelMap.put("del", 0);
//            modelMap.put("warehouseIdIn", dataIdIn);
//            modelMap.put("numOverZero", true);
//            Integer count = productWarehouseModel.getEntitysCount(modelMap);
//            if (Objects.isNull(count)) {
//                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
//            }
//
//            if (count > 0) {
//                throw new XbbException(ErrorCodeEnum.API_ERROR_244010);
//            }
            Map<String, String> noAndName= new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //查询名称
            BoolQueryBuilder productBuilder = boolQuery();
            // 添加corpid,formId,del
            productBuilder.filter(termQuery("corpid.keyword", corpid));
            productBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            productBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.SERIALNO.getAlias());
            fieldList.add(WarehouseEnum.getAttrConnectData(WarehouseEnum.WAREHOUSE_NAME));
            List<PaasFormDataEntityExt> extList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE, productBuilder, PaasFormDataEntityExt.class, fieldList);
            for (PaasFormDataEntityExt contract : extList) {
                JSONObject data = contract.getData();
                String no = contract.getSerialNo();
                String name = FastJsonHelper.getStringOrDefaultFromFormData(data, WarehouseEnum.WAREHOUSE_NAME.getAttr(), "");
                noAndName.put(no, name);
            }

             if(!dataIdIn.isEmpty()) {
                 if(BasicConstant.ONE.equals(warehouseDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(dataIdIn.size())){
                    warehouseModel.deleteByKey(dataIdIn.get(0),corpid);
                 }else {
                    warehouseModel.deleteBatch(dataIdIn, corpid);
                 }
                 warehouseDeleteBatchVO.setDeleteIds(dataIdIn);
                 Runnable runnable = () -> {
                     try {
                         Integer start = 0;
                         Integer pageNum = 1000;
                         // 分页删除产品库存
                         Map<String, Object> productWarehouseParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                         productWarehouseParam.put("corpid", corpid);
                         productWarehouseParam.put("del", 0);
                         productWarehouseParam.put("warehouseIdIn", dataIdIn);
                         productWarehouseParam.put("start", start);
                         productWarehouseParam.put("pageNum", pageNum);
                         while (true) {
                             // 每次搜1000去删除，不需要对start进行计算
                             List<ProductWarehouseEntity>  list = productWarehouseModel.findEntitysWithWarehouseChecked(productWarehouseParam,null);
                             if (Objects.isNull(list) || list.size() == 0) {
                                 break;
                             }
                             productWarehouseModel.deleteByIdInAndParentId(corpid, list);
                         }
                         // 分页删除产品库存
                         productWarehouseParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                         productWarehouseParam.put("corpid", corpid);
                         productWarehouseParam.put("del", 0);
                         productWarehouseParam.put("warehouseIdIn", dataIdIn);
                         productWarehouseParam.put("start", start);
                         productWarehouseParam.put("pageNum", pageNum);
                         while (true) {
                             // 每次搜1000去删除，不需要对start进行计算
                             List<ProductStockEntity>  list = productStockModel.findEntitys(productWarehouseParam);
                             if (Objects.isNull(list) || list.size() == 0) {
                                 break;
                             }
                             productStockModel.deleteByIdIn(corpid,list);
                         }
                     } catch (Exception e) {
                         LOG.error("删除产品库存", e);
                     }
                 };
                 threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                 oriStockService.deleteByWarehouseId(corpid,dataIdIn);
            }

            //生成删除日志(区分单个删除和批量删除)
            String userId = warehouseDeleteBatchDTO.getUserId();
            String userName = warehouseDeleteBatchDTO.getLoginUserName();
            List<String> list = new ArrayList<>();
            Iterator<String> iterator = noAndName.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = noAndName.get(key);
                if(StringUtil.isEmpty(value)){
                    list.add(key);
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append(key).append("（").append(value).append("）");
                    list.add(sb.toString());
                }
            }
            OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
            if (Objects.equals(1, warehouseDeleteBatchDTO.getIsBusinessRule())) {
                operateTypeEnum = OperateTypeEnum.RULE_DELETE;
            }
            String nameStr = StringUtils.join(list, "，");
            if(dataIdIn.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.WAREHOUSE.getName(), dataIdIn.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(WarehouseEnum.WAREHOUSE_NO.getAttrName());
                infoArrPojo.setContent(nameStr);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.WAREHOUSE, operateTypeEnum,
                        "", "", memo, warehouseDeleteBatchDTO.getHttpHeader());
            } else if (Objects.equals(dataIdIn.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.WAREHOUSE.getName(), nameStr);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.WAREHOUSE, operateTypeEnum,
                        dataIdIn.get(0).toString(), nameStr, memo, warehouseDeleteBatchDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("删除仓库失败：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return warehouseDeleteBatchVO;
    }

    /**
     * 关联库存单据校验
     * @param warehouseList
     * @param dataIdSet
     * @param corpid
     * @throws XbbException
     */
    private void checkStockDoc(List<WarehouseEntityExt> warehouseList, Set<Long> dataIdSet, String corpid) throws XbbException {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID,corpid);
        param.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
        param.put("warehouseIdIn",dataIdSet);
        param.put("pageSize",1);
        List<InstockProductEntity> instockProductEntityList = instockProductModel.findEntitys(param);
        for (InstockProductEntity entity : instockProductEntityList) {
            for (WarehouseEntityExt warehouseEntityExt : warehouseList) {
                if (Objects.equals(warehouseEntityExt.getId(),entity.getWarehouseId())) {
                    throw new XbbException(ProductErrorCodeEnum.API_ERROR_205064,String.format(ProductErrorCodeEnum.API_ERROR_205064.getMsg(),warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
                }
            }
        }
        List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
        for (OutstockProductEntity entity : outstockProductEntityList) {
            for (WarehouseEntityExt warehouseEntityExt : warehouseList) {
                if (Objects.equals(warehouseEntityExt.getId(),entity.getWarehouseId())) {
                    throw new XbbException(ProductErrorCodeEnum.API_ERROR_205065,String.format(ProductErrorCodeEnum.API_ERROR_205065.getMsg(),warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
                }
            }
        }
        List<WarehouseOristockEntity> warehouseOristockEntityList = warehouseOristockModel.findEntitys(param);
        for (WarehouseOristockEntity entity : warehouseOristockEntityList) {
            for (WarehouseEntityExt warehouseEntityExt : warehouseList) {
                if (Objects.equals(warehouseEntityExt.getId(),entity.getWarehouseId())) {
                    throw new XbbException(ProductErrorCodeEnum.API_ERROR_205066,String.format(ProductErrorCodeEnum.API_ERROR_205066.getMsg(),warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr())));
                }
            }
        }
    }

    @Override
    public List<Long> getWarehouseIdsByPermission(UserVO loginUser, Set<DepartmentVO> depSet) throws XbbException {
        return warehouseModel.getWarehouseIdsByPermission(loginUser, depSet);
    }

    @Override
    public List<PaasFormDataEntityExt> getWarehouseByPermission(UserVO loginUser, Set<DepartmentVO> depSet) throws XbbException {
        String corpid = loginUser.getCorpid();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        if (!loginUser.isMaxDataPermission()){
            List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditionList, loginUser, XbbRefTypeEnum.WAREHOUSE.getCode(),depSet);
            EsUtil.parseShouldCondition(boolQueryBuilder,shouldConditionList,"",corpid,XbbRefTypeEnum.WAREHOUSE.getCode());
        }
        return (List<PaasFormDataEntityExt>) esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,PaasFormDataEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
    }

    @Override
    public void updateBatchLabelAttr(AddLabelDTO addLabelDTO, List<PaasFormDataEntityExt> addBatchList, Boolean addOrDelete) throws XbbException {
        WarehouseUpdateBatchDTO warehouseUpdateBatchDTO = new WarehouseUpdateBatchDTO();
        BeanUtil.copyProperties(addLabelDTO, warehouseUpdateBatchDTO);
        List<WareHouseUpdateDTO> wareHouseUpdateList = new ArrayList<>();
        addBatchList.forEach(item->{
            WareHouseUpdateDTO wareHouseUpdateDTO = new WareHouseUpdateDTO();
            wareHouseUpdateDTO.setData(item.getData());
            wareHouseUpdateDTO.setId(item.getId());
            wareHouseUpdateList.add(wareHouseUpdateDTO);
        });
        warehouseUpdateBatchDTO.setWareHouseUpdateDTOList(wareHouseUpdateList);
        // updateBatch(supplierContactUpdateBatchDTO);
        updateBatch(warehouseUpdateBatchDTO);
    }

    @Override
    public void batchEditAttr(WareHouseEditAttrUpdateDTO wareHouseEditAttrUpdateDTO) throws XbbException {
        MarketActivityEditAttrUpdateVO marketActivityEditAttrUpdateVO = new MarketActivityEditAttrUpdateVO();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(wareHouseEditAttrUpdateDTO, true);
            param.put("idIn", wareHouseEditAttrUpdateDTO.getDataIdList());
            List<WarehouseEntityExt> warehouseEntityExts = warehouseModel.findEntitys(param);

            if(Objects.isNull(warehouseEntityExts)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            // 仓库不支持审批审批通过后是否允许编辑
            // boolean editAfterFinished = paasProcessTemplateModel.getEditAfterFinished(marketActivityEditAttrUpdateDTO.getAppId(),marketActivityEditAttrUpdateDTO.getMenuId(),marketActivityEditAttrUpdateDTO.getFormId(),marketActivityEditAttrUpdateDTO.getLoginUser());
            List<PaasFormDataEntityExt> dataList = new ArrayList<>(warehouseEntityExts);
            // 审批后能否编辑
            // paasProcessTemplateModel.checkEditAfterFinished(editAfterFinished, dataList);
            List<Long> updateIdList = new ArrayList<>();
            List<WareHouseUpdateDTO> wareHouseUpdateDTOS = new ArrayList<>();
            wareHouseEditAttrUpdateDTO.getDataIdList().forEach((item)->{
                WareHouseUpdateDTO wareHouseUpdateDTO = new WareHouseUpdateDTO();
                wareHouseUpdateDTO.setId(item);
                updateIdList.add(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(wareHouseEditAttrUpdateDTO.getFieldEditedList());
                wareHouseUpdateDTO.setData(data);
                wareHouseUpdateDTOS.add(wareHouseUpdateDTO);
            });
            if (!wareHouseUpdateDTOS.isEmpty()) {
                WarehouseUpdateBatchDTO warehouseUpdateBatchDTO = new WarehouseUpdateBatchDTO();
                BeanUtil.copyProperties(wareHouseEditAttrUpdateDTO, warehouseUpdateBatchDTO);
                warehouseUpdateBatchDTO.setWareHouseUpdateDTOList(wareHouseUpdateDTOS);
                updateBatch(warehouseUpdateBatchDTO);
                marketActivityEditAttrUpdateVO.setUpdateIdList(updateIdList);
            }
            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (WarehouseEntityExt item : warehouseEntityExts) {
                dataIdList.add(item.getId());
                JSONObject data = item.getData();
                String serialNo = item.getSerialNo();
                String opObjectName = data.getString(MarketActivityEnum.NAME.getAttr());
                StringBuilder sb = new StringBuilder();
                opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                updataItemList.add(opObjectName);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = wareHouseEditAttrUpdateDTO.getUserId();
            String corpid = wareHouseEditAttrUpdateDTO.getCorpid();
            String loginUserName = wareHouseEditAttrUpdateDTO.getLoginUserName();
            // 标签特殊处理
            Integer fieldType = wareHouseEditAttrUpdateDTO.getFieldType();
            Boolean isFieldDependence = wareHouseEditAttrUpdateDTO.getIsFieldDependence();
            logHelp.analysisLabel(corpid, fieldType, isFieldDependence,wareHouseEditAttrUpdateDTO.getLogFieldEditedList());

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(wareHouseEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.MARKET_ACTIVITY.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.WAREHOUSE, OperateTypeEnum.EDIT,
                        "", "", memo, wareHouseEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.MARKET_ACTIVITY.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.WAREHOUSE, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, wareHouseEditAttrUpdateDTO.getHttpHeader());
            }
        } catch (XbbException e){
            throw e;
        } catch (Exception e) {
            LOG.error("wareHouseServiceImpl.batchEditAttr 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        String corpid = saasFormSaveDTO.getCorpid();
        JSONObject newData = saasFormSaveDTO.getNewData();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long warehouseId = newPaasFormDataEntity.getId();
        JSONArray depArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_DEP_ID.getAttr());
        JSONArray userArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_ID.getAttr());
        List<Long> depList = new ArrayList<>();
        List<String> userList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (depArray != null) {
            depList = depArray.toJavaList(Long.class);
        }
        if (userArray != null) {
            userList = userArray.toJavaList(String.class);
        }
        // 建立仓库协同团队
        buildWarehouseTeam(corpid, userList, depList, warehouseId, param);
    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        String corpid = saasFormSaveDTO.getCorpid();
        JSONObject newData = saasFormSaveDTO.getNewData();
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long warehouseId = newPaasFormDataEntity.getId();
        JSONArray depArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_DEP_ID.getAttr());
        JSONArray userArray = FastJsonHelper.getJsonArrFromFormData(newData, WarehouseEnum.MANAGER_ID.getAttr());
        List<Long> depList = new ArrayList<>();
        List<String> userList = new ArrayList<>();
        List<String> containUserIdList = new ArrayList<>();
        List<Long> containDepIdList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (depArray != null) {
            depList = depArray.toJavaList(Long.class);
        }
        if (userArray != null) {
            userList = userArray.toJavaList(String.class);
        }
        // 编辑仓库时删除删掉的负责人和负责部门
        deleteOldWarehouseUserList(corpid, warehouseId, depList, userList, containUserIdList, containDepIdList, param);
        userList.removeAll(containUserIdList);
        depList.removeAll(containDepIdList);
        // 建立仓库协同团队
        buildWarehouseTeam(corpid, userList, depList, warehouseId, param);
    }

    private void updateBatch(WarehouseUpdateBatchDTO warehouseUpdateBatchDTO) throws XbbException {
        try {
            String corpid = warehouseUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<WareHouseUpdateDTO> wareHouseUpdateDto = warehouseUpdateBatchDTO.getWareHouseUpdateDTOList();
            if (Objects.nonNull(wareHouseUpdateDto) && !wareHouseUpdateDto.isEmpty()) {
                wareHouseUpdateDto.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                warehouseModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("wareHouseServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void updateBatchByBusinessRule(WarehouseUpdateByBusinessRuleDTO warehouseUpdateByBusinessRuleDTO) throws XbbException {
        try {
            String corpid = warehouseUpdateByBusinessRuleDTO.getCorpid();
            List<PaasFormDataEntityExt> formDataList = warehouseUpdateByBusinessRuleDTO.getFormDataList();
            List<UpdateDataEntity> updateList = ExplainUtil.getUpdateValueByBusinessRule(formDataList, corpid, warehouseUpdateByBusinessRuleDTO.getOperations());

            if (!updateList.isEmpty()) {
                warehouseModel.updateBatch(updateList, corpid);
                RuleBusinessLogDTO businessLogDTO = new RuleBusinessLogDTO();
                BeanUtil.copyProperties(warehouseUpdateByBusinessRuleDTO, businessLogDTO);
                businessLogDTO.setFormDataList(formDataList);
                ruleBusinessLogger.writeLog(businessLogDTO, updateList);
            }
        } catch (Exception e) {
            LOG.error("warehouseService.updateFormDataByBusinessRule根据业务规则更新数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void updateProductLinkWarehouseName(String corpid, Long dataId, String warehouseName) throws XbbException {
        HashMap<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("warehouseId", dataId);
        List<ProductWarehouseEntity> productWarehouseList = productWarehouseModel.findEntitysWithWarehouseChecked(param,null);
        Set<Long> parentProductIdSet = new HashSet<>();
        productWarehouseList.forEach(item -> parentProductIdSet.add(item.getParentId()));

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("dataId", parentProductIdSet));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
        fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.WAREHOUSE));
        fieldList.add(ProductEnum.getAttrConnectData(ProductEnum.WAREHOUSE_LINK_TEXT));
        List<PaasFormDataEntity> parentProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);

        // 更新产品表里的关联仓库字段
        List<UpdateDataEntity> updateDataEntityList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : parentProductList) {
            List<String> warehouseIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntity.getData(), ProductEnum.WAREHOUSE.getAttr(), new JSONArray()).toJavaList(String.class);
            List<String> warehouseNameArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntity.getData(), ProductEnum.WAREHOUSE_LINK_TEXT.getAttr(), new JSONArray()).toJavaList(String.class);
            updateProductWarehouse(corpid, dataId, warehouseName, updateDataEntityList, paasFormDataEntity, warehouseIdArr, warehouseNameArr);
        }
        if (CollectionUtils.isNotEmpty(updateDataEntityList)) {
            productModel.updateBatch(updateDataEntityList, corpid);
        }
    }


    private void updateProductWarehouse(String corpid, Long warehouseId, String warehouseName, List<UpdateDataEntity> updateDataEntityList, PaasFormDataEntity paasFormDataEntity, List<String> warehouseIdArr, List<String> warehouseNameArr) {
        if (Objects.nonNull(warehouseIdArr) && warehouseIdArr.contains(warehouseId.toString())) {
            int index = warehouseIdArr.indexOf(warehouseId.toString());
            warehouseNameArr.set(index, warehouseName);
            JSONObject data = new JSONObject();
            data.put(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr(), warehouseNameArr);
            updateDataEntityList.add(ExplainUtil.getUpdateData(paasFormDataEntity.getId(), data, corpid));
        }
    }
}
